using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Transactions;
using System.Data.Entity.Core.Metadata.Edm;

namespace NeuroSpeech.WebAtoms.Mvc
{
    public class EntityInfo
    {

        public PropertyInfo Identity { get; private set; }

        public PropertyInfo[] Keys { get; private set; }

        public Type Type { get; private set; }

        static Dictionary<Type, EntityInfo> cache = new Dictionary<Type, EntityInfo>();

        internal static EntityInfo Get(MetadataWorkspace ws, Type type)
        {
            EntityInfo e = null;
            lock (cache)
            {
                if (cache.TryGetValue(type, out e))
                    return e;
            }

            e = new EntityInfo { };
            var entity = ws.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(x => x.Name == type.Name);
            var keys = entity.KeyMembers.Select(x => x.Name);

            var id = entity.Properties.Where(x => x.MetadataProperties.Any(y => y.Name == "http://schemas.microsoft.com/ado/2009/02/edm/annotation:StoreGeneratedPattern")).Select(y => y.Name).FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(id))
            {
                e.Identity = type.GetProperty(id);
            }

            e.Keys = keys.Select(x => type.GetProperty(x)).ToArray();
            e.Type = type;
            lock (cache)
            {
                cache[type] = e;
            }
            return e;
        }
    }
}
